package com.my.code.sort;

import java.util.Arrays;

/**
 * 归并排序<br>
 * 该算法采用的分治思想，先递归拆分，再合并。要使用额外的内存空间。
 *
 * @author zzl
 * @date 2020/10/16
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        int[] tmp = new int[arr.length];
        sort(arr, 0, arr.length - 1, tmp);
    }

    private static void sort(int[] arr, int left, int right, int[] tmp) {
        if (left < right) {
            int mid = (left + right) / 2;
            sort(arr, left, mid, tmp);//递归拆分左侧
            sort(arr, mid + 1, right, tmp);//递归拆分右侧
            merge(arr, left, mid, right, tmp);//合并左侧和右侧
        }
    }

    private static void merge(int[] arr, int left, int mid, int right, int[] tmp) {
        int i = left;//左指针
        int j = mid + 1;//右序列指针
        int t = 0;//临时数组指针

        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                tmp[t++] = arr[i++];
            } else {
                tmp[t++] = arr[j++];
            }
        }

        while (i <= mid) tmp[t++] = arr[i++];//左边剩余填充
        while (j <= right) tmp[t++] = arr[j++];//右边剩余填充

        t = 0;
        while (left <= right) arr[left++] = tmp[t++];//将tmp中的元素全部拷贝到原数组中
    }

}
